const mammoth = require('mammoth')
const fs = require('fs')
const { template, CONTENT_FLAG,getDyTemplate } = require('./htmlTemplate')
const chalk = require('chalk')

const options = require('./styleMap')

function convertToHtml(filePath) {
  return mammoth
    .convertToHtml({ path: filePath }, options)
    .then(function (result) {
      let tmp = process.env.NODE_ENV === 'development' ? getDyTemplate() : template
      return tmp.replace(CONTENT_FLAG, result.value)
    })
    .catch((err) => {
      console.log('convertToHtml err', err)
    })
}

function buildHtml(docxPath, outputPath) {
  return new Promise(function (resolve) {
    convertToHtml(docxPath).then((res) => {
      const outputStream = outputPath
        ? fs.createWriteStream(outputPath)
        : process.stdout
      outputStream.write(res, function (err) {
        if (err) {
          console.error(err)
          process.exit(0)
        } else {
          console.log(`\n[${new Date().toLocaleTimeString()}] ${chalk.green('buildHtml success ' + (outputPath || ''))}\n`)
          resolve(true)
        }
      })
      return res
    })
  })
}

module.exports = buildHtml
